import { Space, Table, Tag, Button, Modal, Popover, Switch } from 'antd'
import { DeleteOutlined, EditOutlined, ExclamationCircleOutlined } from '@ant-design/icons'
import type { ColumnsType } from 'antd/es/table'
import React, { useEffect, useState } from 'react'
import axios from '../../../utils/request'
import PubSub from 'pubsub-js'
const { confirm } = Modal

interface DataType {
  key: string
  title: string
  label: string
  id: number
  grade: number
  children?: DataType[]
  pagepermisson?: number
  rightId?: number
}

const App: React.FC = () => {
  const [rightList, setrightList] = useState<DataType[]>([])
  function getData() {
    axios.get('/rights?_embed=children').then(({ data }) => {
      data.forEach((item: DataType) => {
        if (item.children?.length === 0) delete item.children
      })
      setrightList(data)
    })
  }
  useEffect(() => {
    getData()
  }, [])
  const showDeleteConfirm = (item: DataType) => {
    confirm({
      title: 'Are you sure delete this task?',
      icon: <ExclamationCircleOutlined />,
      content: 'Some descriptions',
      okText: 'Yes',
      okType: 'danger',
      cancelText: 'No',
      onOk() {
        return axios.delete(`/${item.grade === 1 ? 'rights' : 'children'}/${item.id}`).then(() => {
          getData()
          PubSub.publish('updData')
        })
      },
      onCancel() {
        console.log('Cancel')
      },
    })
  }
  const columns: ColumnsType<DataType> = [
    {
      title: 'ID',
      dataIndex: 'id',
    },
    {
      title: '权限名称',
      dataIndex: 'label',
    },
    {
      title: '权限路径',
      dataIndex: 'key',
      render: (item: string) => <Tag color="orange">{item}</Tag>,
    },
    {
      title: 'Action',
      render: (item: DataType) => (
        <Space size="middle">
          <Button type="primary" danger ghost shape="circle" icon={<DeleteOutlined />} onClick={() => showDeleteConfirm(item)} />
          <Popover
            content={
              <div style={{textAlign: 'center'}}>
                <Switch checked={item.pagepermisson === 1} onChange={() => {
                  axios.patch(`/${item.grade === 1 ? 'rights' : 'children'}/${item.id}`,{ pagepermisson: item.pagepermisson === 0 ? 1 : 0 })
                  .then(() => {
                    getData()
                    PubSub.publish('updData')
                    PubSub.publish('updRoute')
                  })
                }}/>
              </div>
            }
            title="页面配置项"
            trigger={item.pagepermisson !== undefined ? 'click': ''}
          >
            <Button type="primary" shape="circle" icon={<EditOutlined />} disabled={item.pagepermisson === undefined}/>
          </Popover>
        </Space>
      ),
    },
  ]
  return <Table columns={columns} dataSource={rightList} pagination={{ pageSize: 10 }} />
}

export default App
